<?php

class CResponse{
	
	private $_views = array();
	
	/**
	 * @var CPage
	 */
	public $_page;
	public $_model;
	/**
	 * 
	 * @var IBaseUser
	 */
	public $_user;
	
	public $_default_view;
	
	public function __construct(){
		$this->buildPage();
	}
	
	public function addView($view, $model){
		$item = new CViewRender($view, $model);
		array_push($this->_views, $item);
	}
	
	public function render($model=null){
		//Busca si la accion cuenta con vista cargada
		if($this->_default_view==null){
			//Error no se cargo ninguna vista
			Debug::Write(
			"Error. ".get_class($this).":render; No se cargo vista al render y no cuenta con vista default.");
		}else{
			if($model)
			{ $this->addView($this->_default_view, $model); }
		}
		
		include APP_PATH.Config::$opt['app']['path_layout'].App::$Request->_layout;
		
		die();
	}
	
	public function loadViews(){
		foreach($this->_views as $view){
			$this->_model = $view->_model;
			include APP_PATH.Config::$opt['app']['path_view'].$view->_view;
		}
	}
	
	private function buildPage(){
		$this->_page = new CPage();
		
		$directory = substr(
		$_SERVER['SCRIPT_NAME'],
		0,
		strrpos($_SERVER['SCRIPT_NAME'], "/") + 1);
		
		$protocol = ($_SERVER['HTTPS'] & $_SERVER['HTTPS']!='off') ? "https" : "http";
		
		$this->_page->baseUrl = $protocol . "://" . $_SERVER['HTTP_HOST'].$directory;
		$this->_page->baseImageUrl = $this->_page->baseUrl.Config::$opt['view']['path_img'];
		$this->_page->baseCssUrl = $this->_page->baseUrl.Config::$opt['view']['path_css'];
		$this->_page->baseJsUrl = $this->_page->baseUrl.Config::$opt['view']['path_js'];
		
		$this->_page->divCommander = Config::$opt['enviroment']['div_command'];
		$this->_page->divModalInfo = Config::$opt['enviroment']['div_modal_info'];
	}
	
	public function redirect($command, $action, $layout=null, $params=null){
		$url = self::makeUrl($command, $action, $layout, $params);
		header("Location: ".$url);
		die();
	}

	public function makeUrl($command=null, $action=null, $layout=null, $params=null){
		$command = ($command) ? $command : App::$Request->_command;
		$action = ($action) ? $action : App::$Request->_action;
		$layout = ($layout) ? $layout : App::$Request->_layout;
		$params = ($params) ? $params : array();
		
		$url = $this->_page->baseUrl."index.php?kn_ctrl=$command&kn_actn=$action";
		
		if($layout!=Config::$opt['view']['base_layout'])
		{ $url .= "&kn_nmly=$layout"; }
		
		foreach($params as $item => $value)
		{ $url .= "&$item=".urlencode($value); }
		
		return $url;
	}
}